

#include "Socket.h"
#include "Select.h"
#include "Tools.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>


static CSelect *        selectA = NULL;
static CSocket          sockL(CSocket::eSocketType_TCP);


static int socket_read_proc(CSocket * sock)
{
        char    buf[1025];
        int     ret;

        const char * bash = "220 (False TP 1.0)\n";
        const char * user = "331 Please specify the password.\n";
        const char * pass = "230 Login successful.\n";
        const char * type = "220 Type set to: Binary\n";
        const char * port = "421 Service not available. Connection Closed.\n";


        if(sock == &sockL)
        {
                CSocket *       s = new CSocket(CSocket::eSocketType_TCP);
                sock->Accept(*s);
                selectA->AddReadSocket(s);
                s->Send(bash, strlen(bash));
                return 0;
        }

        memset(buf, 0, 1025);
        ret = sock->Recv(buf, 1024);
        buf[ret] = '\0';

        printf("%s",  buf);
        fflush(stdout);
        if(strncmp(buf, "USER", 4) == 0)
        {
                sock->Send(user, strlen(user));
        } else if (strncmp(buf, "PASS", 4) == 0) {
                sock->Send(pass, strlen(pass));
        } else if (strncmp(buf, "TYPE", 4) == 0) {
                sock->Send(type, strlen(type));
        } else if (strncmp(buf, "PORT", 4) == 0) {
                sock->Send(port, strlen(port));
                selectA->DelReadSocket(sock);
                sock->Close();
        }
        return 0;
}


int main(void)
{
#if defined(_WIN32) || defined(WIN32)
        WORD            wVersionRequested;
        WSADATA         wsaData;
        int             err;
        wVersionRequested = MAKEWORD(2, 2);
        err = WSAStartup(wVersionRequested, &wsaData);
        if(err != 0)
        {
                Debug() << "Couldn't find a usable winsock.dll\n" << endl;
                return -1;
        }
#endif

        selectA = new CSelect();
        try
        {
                sockL.Create();
                sockL.Bind(21);
                sockL.Listen();
                selectA->AddReadSocket(&sockL);
                selectA->SetTimeout(100);
                selectA->RegisterReadCallback(socket_read_proc);
                selectA->Run();
        } catch(const char * e) {
                PRINTF("%s\n", e);
        }
        delete selectA;
        return 0;
}

